package com.quanyan.ic.vendingMachine.protocol.server;

import com.quanyan.ic.common.spring.SpringUtil;
import com.quanyan.ic.vendingMachine.protocol.codec.protobuf.VmMessageProto;
import com.quanyan.ic.vendingMachine.protocol.server.handler.HandShakeRespHandler;
import com.quanyan.ic.vendingMachine.protocol.server.handler.HeartBeatRespHandler;
import com.quanyan.ic.vendingMachine.protocol.server.handler.ShipGoodsRespHandler;
import com.quanyan.ic.vendingMachine.protocol.server.handler.UpdateCmdRespHandler;
import com.quanyan.ic.vendingMachine.protocol.server.session.SessionManager;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhuo.shi on 2017/7/28.
 * 自动售卖机服务启动类
 */
public class VmServer {

    private static Logger logger = LoggerFactory.getLogger(VmServer.class);

    private int port;
    private SessionManager sessionManager;

    public void start() {
        NioEventLoopGroup boss = new NioEventLoopGroup(0, new NamedThreadFactory("vm-server-boss", true));
        NioEventLoopGroup worker = new NioEventLoopGroup(0, new NamedThreadFactory("vm-server-worker", true));

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new ProtobufVarint32FrameDecoder());       //半包处理
                        pipeline.addLast(new ProtobufDecoder(VmMessageProto.VmMessage.getDefaultInstance()));       //解码器(目标类)
                        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());       //对协议的的消息头上加上一个长度为32的整形字段，用于标志这个消息的长度。
                        pipeline.addLast(new ProtobufEncoder());        //给应答消息编码
                        pipeline.addLast(SpringUtil.getBean("HandShakeRespHandler", HandShakeRespHandler.class));   //握手处理
                        pipeline.addLast(SpringUtil.getBean("HeartBeatRespHandler", HeartBeatRespHandler.class));   //心跳处理
                        pipeline.addLast(SpringUtil.getBean("ShipGoodsRespHandler", ShipGoodsRespHandler.class));   //出货业务处理
                        pipeline.addLast(SpringUtil.getBean("UpdateCmdRespHandler", UpdateCmdRespHandler.class));   //更新升级
                    }
                });

        try {
            ChannelFuture f = serverBootstrap.bind(port).sync();
            logger.info("Vm server started on port(s): {} (tcp) ", port);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("Vm server start failed: {}", e.getMessage());
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public SessionManager getSessionManager() {
        return sessionManager;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }
}

class NamedThreadFactory implements ThreadFactory {

    private final static AtomicInteger poolNumber = new AtomicInteger(1);
    private final static AtomicInteger threadNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final String namePrefix;
    private final boolean isDaemon;

    public NamedThreadFactory(String name) {
        this(name, false);
    }

    protected NamedThreadFactory(String prefix, boolean daemon) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = prefix + "-" + poolNumber.getAndIncrement() + "-thread-";
        isDaemon = daemon;
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        t.setDaemon(isDaemon);
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}

